from models import LineItem


class Cart(object):

    def __init__(self):
        self.items = []
        self.total_price = 0

    def add_book(self, book):
        self.total_price += book.price
        for item in self.items:
            if item.book.id == book.id:
                item.quantity += 1
                return
        self.items.append(LineItem(book=book,
                                   unit_price=book.price,
                                   quantity=1))

    def delete_book(self, book):
        self.total_price -= book.price
        for item in self.items:
            if item.book.id == book.id:
                item.quantity -= 1
                if item.quantity == 0:
                    self.items.remove(item)
                return
